import React, { useState, useEffect, useRef, useCallback } from "react";
import { flushSync } from "react-dom";
import styles from "./index.module.less";
import {
  NavBar,
  Avatar,
  Space,
  Toast,
  Dialog,
  PullToRefresh,
} from "antd-mobile";
import {
  SendOutlined,
  OpenAIOutlined,
} from "@ant-design/icons";
import {
  AddOutline,
  UpOutline,
  RightOutline,
  DeleteOutline,
  RedoOutline,
  EditSOutline,
  ClockCircleOutline,
} from "antd-mobile-icons";
import { useSearchParams } from "react-router-dom";
import ModelSelector from "@/components/ModelSelector";
import HeaderNav from "@/components/header-nav";
const {
  getChatDetail,
  postChatMessage,
  deleteChatMessage,
  saveChatMessage,
  editChatMessage,
  batchDeleteChatMessage,
  getChatPostMessageUrl
} = $globalServicer("chat");
import { Bubble, Sender } from "@ant-design/x";
import { XRequest } from "@ant-design/x";
import { produce } from "immer";
import dayjs from "dayjs";
import EditModal from "@/components/editModal";
const baseURL = `${import.meta.env.VITE_BASE_URL}/user/chat/new/generate`;
const responseErrorMessage = "456非常抱歉，您发送的内容违反了相关法律法规以及内容安全规定，我无法对这类内容做出回应。我们应当共同维护一个健康、文明、积极向上的交流环境 ，如果您有其他合规的问题或话题，随时都能问我。";
// 创建自定义fetch函数，添加认证头部并处理错误响应
const customFetch = async (input, init) => {
  const token = localStorage.getItem("access_token");
  const customHeaders = {
    "Content-Type": "application/json",
    ...(token && {
      "Authorization": `bearer ${token}`,
      "auth_header": `Basic cm9vdDpyb290`
    }),
    ...init?.headers, // 保留原有的headers
  };

  const customInit = {
    ...init,
    headers: customHeaders,
  };

  const response = await fetch(input, customInit);
  
  // 添加调试日志
  console.log("🚀 ~ customFetch ~ 响应状态:", {
    url: input,
    status: response.status,
    ok: response.ok,
    contentType: response.headers.get('content-type')
  });
  
  // 如果响应不成功，尝试解析错误详情
  if (!response.ok) {
    let errorDetails = null;
    
    try {
      // 检查内容类型，只有 JSON 格式才解析
      const contentType = response.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        console.warn("错误响应不是JSON格式:", contentType);
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      
      // 尝试解析响应体中的错误信息
      const errorData = await response.json();
      console.log("🚀 ~ customFetch ~ 错误响应数据:", errorData);
      
      errorDetails = {
        status: response.status,
        statusText: response.statusText,
        data: errorData
      };
      
      // 构造详细的错误信息
      let errorMessage = `请求失败 (${response.status})`;
      
      if (errorData.code) {
        errorMessage += ` - 错误码: ${errorData.code}`;
      }
      
      if (errorData.error || errorData.message) {
        errorMessage = errorData.error || errorData.message;
      }
      
      // 创建包含详细信息的错误对象
      const error = new Error(errorMessage);
      error.status = response.status;
      error.code = errorData.code;
      error.details = errorData;
      
      throw error;
      
    } catch (parseError) {
      // 如果无法解析JSON，使用默认错误信息
      if (parseError instanceof SyntaxError) {
        console.warn("无法解析错误响应JSON:", parseError);
        const error = new Error(`HTTP ${response.status}: ${response.statusText}`);
        error.status = response.status;
        throw error;
      } else {
        // 如果是我们主动抛出的错误，直接重新抛出
        throw parseError;
      }
    }
  }
  
  return response;
};

// 创建XRequest实例
const createXRequestInstance = (baseURL) => {
  return XRequest({
    baseURL,
    fetch: customFetch,
  });
};

// 错误处理工具函数
const parseErrorMessage = (error) => {
  
  // 如果是 AbortError，不需要处理
  if (error.name === "AbortError") {
    return null;
  }
  
  // 如果 customFetch 已经解析了详细错误信息，直接使用
  if (error.details) {
    console.log("🚀 ~ parseErrorMessage ~ 后端错误详情:", error.details);
    
    // 处理特定的错误码
    if ( [200014,200023,200016 ].includes(error.code) ) {
      return  error.message || "您没有权限使用此模型，请升级会员或选择其他模型!!";
    }
    
    // // 使用后端返回的错误信息
    // if (error.details.error) {
    //   return error.details.error;
    // }
    
    // if (error.details.message) {
    //   return error.details.message;
    // }
  }
  
  // // 如果已经有自定义错误消息，直接返回
  // if (error.message && !error.message.includes("Fetch failed")) {
  //   return error.message;
  // }
  
  // // 解析 HTTP 状态码错误（fallback）
  // if (error.status) {
  //   switch (error.status) {
  //     case 400:
  //       return "请求参数错误，请检查输入内容";
  //     case 401:
  //       return "认证失败，请重新登录";
  //     case 403:
  //       return "权限不足，请联系管理员";
  //     case 404:
  //       return "接口不存在，请联系管理员";
  //     case 429:
  //       return "请求过于频繁，请稍后再试";
  //     case 500:
  //       return "服务器内部错误，请稍后再试";
  //     case 502:
  //       return "网关错误，请稍后再试";
  //     case 503:
  //       return "服务暂时不可用，请稍后再试";
  //     default:
  //       return `请求失败 (${error.status})，请重试`;
  //   }
  // }
  
  // // 网络错误
  // if (error.message && (error.message.includes("Network Error") || error.message.includes("Failed to fetch"))) {
  //   return "网络连接异常，请检查网络";
  // }
  
  // // 超时错误
  // if (error.message && error.message.includes("timeout")) {
  //   return "请求超时，请稍后再试";
  // }
  
  // 默认错误消息
  return "发送消息失败，请重试";
};
// 1. 首先创建一个新的 ChatInput 组件
const ChatInput = React.memo(({ 
  onSend, 
  loading, 
  currentModelId,
  onModelChange,
  modelVisible,
  setModelVisible,
  chatId
}) => {
  const [value, setValue] = useState("");
  
  const handleSubmit = useCallback(async (msg) => {
    if (!msg.trim()) return;
    setValue("");
    await onSend(msg);
  }, [onSend]);

  const senderHeaderPrefix = useCallback(() => (
    <div className={styles.senderHeaderPrefix}>
      <OpenAIOutlined onClick={() => setModelVisible(true)} />
    </div>
  ), [setModelVisible]);

  return (
    <div className={styles.button_wrap}>
      {senderHeaderPrefix()}
      <Sender
        value={value}
        onChange={setValue}
        loading={loading}
        onSubmit={handleSubmit}
        placeholder="发消息，AI生成回复"
        onCancel={() => {
          setLoading(false);
        }}
        actions={(_, info) => {
          const { SendButton, LoadingButton } = info.components;
          if (loading) {
            return <LoadingButton />;
          }
          return (
            <SendButton 
              color="primary" 
              shape="default"
              icon={<SendOutlined />}
            />
          );
        }}
      />
    </div>
  );
});

const Detail = () => {
  const customNavigate = $globalNavigate();
  const [params] = useSearchParams();
  const sendId = params.get("chatId");
  const [chatDetail, setChatDetail] = useState({});
  const listRef = useRef(null);
  const [last_id, setLast_id] = useState(0);
  // chat message
  const [value, setValue] = useState("");
  const [loading, setLoading] = useState(false);
  const [chatMessages, setChatMessages] = useState([]);
  const [displayedMessages, setDisplayedMessages] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 10;
  const [hasMore, setHasMore] = useState(false);
  const [isShowMore, setIsShowMore] = useState(false);
  const [currlentRoles, setCurrentRoles] = useState([
    {
      cover: "",
      name: "",
    },
  ]);
  const [chatPresets, setChatPresets] = useState({
    after: [],
    before: [],
    replace_fields: [],
    chat_num: 0,
  });
  const [editVisible, setEditVisible] = useState(false);
  const [editContent, setEditContent] = useState({
    id: 0,
    message: "",
    send_name: "",
    send_time: "",
    send_cover: "",
  });
  const [chatPersonas, setChatPersonas] = useState({});
  const [modelVisible, setModelVisible] = useState(false);
  const [currentModelId, setCurrentModelId] = useState(0);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [isSendingMessage, setIsSendingMessage] = useState(false);
  const [useStreaming, setUseStreaming] = useState(false);
  const abortController = useRef(null);
  // 1. 首先定义 scrollToBottom 函数（保持原有实现不变）
  const scrollToBottom = (behavior = 'auto') => {
    if (listRef.current && listRef.current.nativeElement) {
      const listElement = listRef.current.nativeElement;
      console.log('===> listElement (native)', listElement);

      // 获取所有消息元素
      const messageElements = Array.from(listElement.querySelectorAll('.ant-bubble[data-message-id]'));
      console.log('===> 所有消息元素:', messageElements.map(el => el.getAttribute('data-message-id')));

      if (messageElements.length > 0) {
        const lastMessageElement = messageElements[messageElements.length - 1];
        const lastMessageId = lastMessageElement.getAttribute('data-message-id');
        console.log('===> 准备滚动到最后一条消息:', {
          id: lastMessageId,
          element: lastMessageElement
        });

        requestAnimationFrame(() => {
          requestAnimationFrame(() => {
             // 使用 'auto' 避免与可能的平滑滚动冲突，'end' 表示对齐元素底部
             lastMessageElement.scrollIntoView({ behavior, block: 'end' });
            //  lastMessageElement.scrollIntoView({ behavior: 'smooth', block: 'end' });
            console.log('===> 滚动执行完成，最后消息ID:', lastMessageId);
          });
        });
      } else {
        console.warn('未找到最后一个消息元素 (.ant-bubble:last-child)');
        // 可以保留之前的 closest + rAF 代码作为备用方案，但我们已知它效果不佳
        // const scrollContainer = listElement.closest('.adm-pull-to-refresh-content');
        // if (scrollContainer) scrollContainer.scrollTop = scrollContainer.scrollHeight;
      }
    }
  };

  // 2. 清理未完成消息的通用函数
  const cleanupUnfinishedMessages = useCallback(() => {
    console.log("🧹 清理未完成的消息");
    
    const cleanupFunction = (prev) => {
      const newMessages = [...prev];
      // 移除最后一条AI消息（如果它是未完成的）
      if (newMessages.length > 0) {
        const lastMessage = newMessages[newMessages.length - 1];
        if (lastMessage.type === 1 && (lastMessage.loading || lastMessage.message === "" || lastMessage.message === "正在思考中...")) {
          console.log("🗑️ 移除未完成的AI消息:", lastMessage);
          newMessages.pop();
        }
      }
      // 同时移除所有loading状态的消息
      return newMessages.filter(msg => !msg.loading);
    };
    
    setChatMessages(cleanupFunction);
    setDisplayedMessages(cleanupFunction);
  }, []);

  // 3. 然后是其他函数的定义
  const saveMessage = useCallback(async (messageData) => {
    try {
      const saveRes = await saveChatMessage({
        chat_id: sendId,
        records: [messageData],
      });
      return saveRes.ids[0];
    } catch (error) {
      console.error("保存消息失败:", error);
      throw error;
    }
  }, [sendId]);

  const isValidRegex = useCallback((pattern) => {
    try {
      new RegExp(pattern);
      return true;
    } catch (e) {
      console.error("Invalid regex pattern:", pattern, e);
      return false;
    }
  }, []);

  // 2. 定义 checkCanSendMessage
  const checkCanSendMessage = useCallback(() => {
    if (currentModelId === 0) {
      Toast.show({
        content: '请先选择一个模型',
      });
      setModelVisible(true);
      return false;
    }
    return true;
  }, [currentModelId, setModelVisible]);
  const abort = () => {
    abortController?.current?.abort?.();
    setIsSendingMessage(false);
  };
  // 3. 定义 sendMessage 函数
  const sendMessage = useCallback(async (content) => {
    try {
      // 1. 准备用户消息
      const userMessage = {
        type: 0,
        send_name: chatPersonas.name,
        send_time: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        message: content,
        loading: false,
        cover: chatPersonas.cover,
      };

      // 2. 保存用户消息并获取ID
      const userMessageData = {
        type: 0,
        message: content,
        send_name: userMessage.send_name,
        send_time: userMessage.send_time,
        send_cover: userMessage.cover,
      };
      const userMessageId = await saveMessage(userMessageData);

      // 3. 更新消息列表
      const updatedFullMessages = [...chatMessages, { ...userMessage, id: userMessageId }];
      const updatedDisplayedMessages = [...displayedMessages, { ...userMessage, id: userMessageId }];
      setChatMessages(updatedFullMessages);
      setDisplayedMessages(updatedDisplayedMessages);

      // 4. 添加AI思考中的临时消息
      const pendingMessage = {
        type: 1,
        message: useStreaming ? "" : "正在思考中...",
        loading: useStreaming ? false : true, // 流式请求时不显示loading状态
        send_name: currlentRoles.name,
        cover: currlentRoles.cover,
        send_time: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        // 为流式消息添加特殊标记，便于识别
        isStreaming: useStreaming,
        isComplete: false,
      };
      setChatMessages([...updatedFullMessages, pendingMessage]);
      setDisplayedMessages([...updatedDisplayedMessages, pendingMessage]);

      // 4.1 在显示用户消息和 Pending 后立即滚动到底部
      setTimeout(() => scrollToBottom('smooth'), 0);

      // 5. 获取AI响应
      const messageData = buildMessageData(updatedFullMessages, chatPresets, content);
      
      // 添加调试信息
      console.log("🚀 ~ sendMessage ~ 请求数据:", {
        baseURL,
        messageData,
        useStreaming,
        chatId: sendId,
        messagesCount: messageData.messages?.length
      });
      
      const xRequestInstance = createXRequestInstance(baseURL);
      let response = null;
      let aiMessage = "";
      let total_tokens = 0;
      let shouldAbortDueToError = false; // 新增标记，指示是否应该因错误而中止

      if (useStreaming) {
        // 流式请求
        let isStreamStarted = false; // 标记流式输出是否已开始
        
        // 高性能流式更新函数
        let shouldAutoScroll = true;
        let scrollCheckCounter = 0;
        
        const immediateUpdate = (message) => {
          // 使用 flushSync 强制同步更新，确保逐字渲染效果
          flushSync(() => {
            const updateFunction = (prev) => 
              produce(prev, draft => {
                const lastMessage = draft[draft.length - 1];
                if (lastMessage?.type === 1) {
                  lastMessage.message = message;
                  lastMessage.loading = false;
                }
              });

            setChatMessages(updateFunction);
            setDisplayedMessages(updateFunction);
          });
          
          // 优化滚动策略：每5个字符检查一次滚动
          scrollCheckCounter++;
          if (scrollCheckCounter % 5 === 0) {
            // 使用微任务确保DOM更新后再滚动
            Promise.resolve().then(() => {
              if (shouldAutoScroll) {
                scrollToBottom('auto');
              }
            });
          }
        };
        
        try {
          await xRequestInstance.create(messageData, {
            onSuccess: () => {
              console.log("流式请求成功完成");
            },
            onError: (error) => {
              console.log("🚀 ~ onError ~ error:", error);
              if (error.name === "AbortError") {
                console.log("请求被中止");
                shouldAbortDueToError = true;
                return;
              }
              
              // 检查是否是需要Toast提示的特定错误码
              const specialErrorCodes = [200014, 200023, 200016];
              const isSpecialError = error.code && specialErrorCodes.includes(error.code);
              
              console.log("🚀 ~ 错误码判断:", {
                errorCode: error.code,
                isSpecialError,
                specialErrorCodes
              });
              
              if (isSpecialError) {
                // 特定错误码：显示Toast提示并标记中止
                console.log("🚀 ~ 执行特定错误码分支 - 显示Toast并中止");
                const errorMessage = parseErrorMessage(error);
                Toast.show({
                  content: errorMessage,
                  type: "error",
                });
                shouldAbortDueToError = true;
              } else {
                // 其他所有错误：统一使用 responseErrorMessage 作为 AI 回复
                console.log("🚀 ~ 执行其他错误分支 - 设置默认回复");
                aiMessage = responseErrorMessage;
                total_tokens = 0;
                isStreamStarted = true; // 标记为已开始，避免被清理
                
                console.log("🚀 ~ 流式请求错误：已设置默认错误消息作为AI回复", {
                  aiMessage: aiMessage.substring(0, 50) + "...",
                });
              }
            },
            onUpdate: (msg) => {
              console.log("收到流式数据:", msg);
              
              // 检查是否完成
              if (msg.data.includes("[DONE]")) {
                // 确保最后的内容被更新
                immediateUpdate(aiMessage);
                return;
              }
              
              try {
                const _msg = JSON.parse(msg.data);
                const deltaContent = _msg?.choices?.[0]?.delta?.content;
                console.log("🚀 ~ onUpdate ~ deltaContent:", deltaContent)
                 if (deltaContent) {
                   aiMessage += deltaContent;
                   console.log("🚀 ~ onUpdate ~ aiMessage:", aiMessage)
                   isStreamStarted = true; // 标记流式输出已开始
                   
                   // 优化更新，平衡性能与体验
                   immediateUpdate(aiMessage);
                 }
                
                // 检查是否有usage信息
                if (_msg?.usage?.total_tokens) {
                  total_tokens = _msg.usage.total_tokens;
                }
              } catch (error) {
                console.error("解析流式数据失败:", error);
              }
            },
            onStream: (controller) => {
              console.log("🚀 ~ onStream ~ controller:", controller)
              abortController.current = controller;
            },
          });
        } catch (streamError) {
          // 捕获 xRequestInstance.create() 本身可能抛出的错误
          console.log("🚀 ~ 流式请求底层错误:", streamError);
          
          // 如果还没有通过 onError 回调处理过错误，在这里处理
          if (!shouldAbortDueToError && !isStreamStarted) {
            // 检查是否是特定错误码
            const specialErrorCodes = [200014, 200023, 200016];
            const isSpecialError = streamError.code && specialErrorCodes.includes(streamError.code);
            
            if (isSpecialError) {
              console.log("🚀 ~ 底层特定错误码处理");
              const errorMessage = parseErrorMessage(streamError);
              Toast.show({
                content: errorMessage,
                type: "error",
              });
              shouldAbortDueToError = true;
            } else {
              console.log("🚀 ~ 底层其他错误处理 - 设置默认回复");
              aiMessage = responseErrorMessage;
              total_tokens = 0;
              isStreamStarted = true;
            }
          }
        }
        
        console.log("🚀 ~ 流式请求完成，检查状态:", {
          shouldAbortDueToError,
          isStreamStarted,
          aiMessage: aiMessage || "空"
        });
        
        // 如果因错误需要中止，清理并返回
        if (shouldAbortDueToError) {
          cleanupUnfinishedMessages();
          return; // 提前返回，不继续执行保存逻辑
        }
        
        // 检查流式输出是否有有效内容，如果没有则使用默认错误消息
        if (!aiMessage || aiMessage.trim() === '') {
          aiMessage = responseErrorMessage;
          total_tokens = 0;
        }
      } else {
        // 非流式请求
        try {
          const response = await postChatMessage(messageData);
          console.log("🚀 ~ sendMessage ~ response:", response)
          // 检查响应内容，如果为空则使用默认错误消息
          if (!response?.choices?.[0]?.message?.content) {
            aiMessage = responseErrorMessage;
            total_tokens = 0;
          } else {
            aiMessage = response.choices[0].message.content;
            total_tokens = response.usage?.total_tokens || 0;
          }
        } catch (error) {
          console.error("非流式请求失败:", error);
          aiMessage = responseErrorMessage;
          total_tokens = 0;
        }
      }
      
      console.log("🚀 6. 处理AI响应消息")
      // 6. 处理AI响应消息
      const replaceFields = chatPresets.replace_fields;
      if (replaceFields.length) {
        replaceFields.forEach((item) => {
          if (item.match_type === "exact") {
            aiMessage = aiMessage.replaceAll(item.search, item?.replace || "");
          }
          if (item.match_type === "regex" && item.search && isValidRegex(item.search)) {
            aiMessage = aiMessage.replaceAll(
              new RegExp(item.search, "g"),
              item?.replace || ""
            );
          }
        });
      }

      // 7. 保存AI响应
      const aiMessageData = {
        type: 1,
        message: aiMessage,
        send_name: pendingMessage.send_name,
        send_time: pendingMessage.send_time,
        send_cover: pendingMessage.cover,
        total_tokens
      };
      const aiMessageId = await saveMessage(aiMessageData);

      // 8. 更新最终消息列表
      const finalAiMessage = {
        ...pendingMessage,
        id: aiMessageId,
        message: aiMessage,
        loading: false,
        isComplete: true,
      };
      
      setChatMessages(prev => {
        const newMessages = [...prev];
        newMessages[newMessages.length - 1] = finalAiMessage;
        return newMessages;
      });
      
      setDisplayedMessages(prev => {
        const newMessages = [...prev];
        newMessages[newMessages.length - 1] = finalAiMessage;
        return newMessages;
      });
      
      setLast_id(aiMessageId);

      // 8.1 在AI回复完成后再次滚动到底部
      setTimeout(() => scrollToBottom('smooth'), 0);

    } catch (error) {
      console.error("发送消息失败:", error);
      
      // 清理未完成的消息
      cleanupUnfinishedMessages();
      
      // 显示错误提示
      const errorMessage = parseErrorMessage(error);
      if (errorMessage) {
        Toast.show({
          content: errorMessage,
          type: "error",
        });
      }
    }
  }, [chatMessages, displayedMessages, chatPresets, currlentRoles, chatPersonas, saveMessage, isValidRegex, scrollToBottom]);

  // 4. 最后定义 handleSendMessage
  const handleSendMessage = useCallback(async (content) => {
    try {
      setIsSendingMessage(true);
      if (!checkCanSendMessage()) {
        return;
      }
      await sendMessage(content);
    } finally {
      setIsSendingMessage(false);
    }
  }, [checkCanSendMessage, sendMessage]);

  const handleModelChange = useCallback((modelId) => {
    setCurrentModelId(modelId);
    getChatDetail(sendId).then((res) => {
      setChatPresets(res.presets);
      setChatDetail(res.detail);
      setUseStreaming(res.mould.stream === 1);
    });
  }, [sendId]);

  useEffect(() => {
    if (loading) {
      const timer = setTimeout(() => {
        setLoading(false);
      }, 3000);

      return () => {
        clearTimeout(timer);
      };
    }
  }, [loading]);

  // 动态角色配置 - 根据消息类型调整
  const getRoles = useCallback((message) => {
    const isStreamingMessage = message?.isStreaming;
    
    return {
      assistant: {
        placement: "start",
        avatar: { icon: <Avatar src={currlentRoles.cover} /> },
        typing: isStreamingMessage ? false : { // 流式消息禁用打字机，非流式启用
          step: 2, 
          interval: 20,
        },
        style: {
          maxWidth: 600,
          marginInlineEnd: 44,
        },
      },
      user: {
        placement: "start",
        avatar: { icon: <Avatar src={chatPersonas.cover} /> },
        style: {
          maxWidth: 600,
          marginInlineEnd: 44,
        },
      },
    };
  }, [currlentRoles.cover, chatPersonas.cover]);

  // 智能角色配置 - 根据流式状态动态调整
  const roles = {
    assistant: {
      placement: "start",
      avatar: { icon: <Avatar src={currlentRoles.cover} /> },
      // 在流式更新时，我们手动控制渲染，因此需要完全禁用组件内置的打字机效果
      // 否则会与我们的 flushSync 逻辑冲突，造成文字块状跳动
      // typing: false,
      typing: { step: 1, interval: 50 },
      style: {
        maxWidth: 600,
        marginInlineEnd: 44,
      },
    },
    user: {
      placement: "start",
      // avatar: { icon: <Avatar src={currlentRoles.cover} /> },
      avatar: { icon: <Avatar src={chatPersonas.cover} /> },
      // typing: { step: 5, interval: 20 },
      style: {
        maxWidth: 600,
        marginInlineEnd: 44,
      },
    },
  };
  const buildMessageData = (chatMessages, presets, currentMessage) => {
    return {
      messages: [
        ...presets?.before,
        ...chatMessages.slice(-presets.chat_num).map((msg) => ({
          role: msg.type === 0 ? "user" : "assistant",
          content: msg.message,
        })),
        {
          role: "user",
          content: currentMessage,
        },
        ...presets?.after,
      ],
      stream: useStreaming,
      chat_id: chatDetail.id,
    };
  };
  const editMessage = useCallback(async (message) => {
    if (!message) return;

    setEditVisible(true);
    setEditContent({
      id: message.id,
      message: message.message,
      send_name: message.send_name,
      send_time: message.send_time,
      send_cover: message.cover,
    });
  }, []);
  const deleteMessage = useCallback(
    async (id, type) => {
      console.log("🚀 ~ deleteChatMessage ~ id:", {
        id: [id],
      });
      // 1 删除单条消息 2 批量删除消息
      const content =
        type === 1 ? "确定要删除此条消息吗？" : "是否回朔到当前剧情重新开始?";
      Dialog.confirm({
        content,
        onConfirm: () => {
          if (type === 1) {
            deleteChatMessage({
              id: id,
            }).then((res) => {
              console.log("🚀 ~ deleteChatMessage ~ res:", res);
              Toast.show({
                content: "删除成功",
                type: "success",
              });
              fetchAndSetInitialMessages(sendId);
            });
          } else {
            batchDeleteChatMessage({
              id: id,
            }).then((res) => {
              console.log("🚀 ~ deleteChatMessage ~ res:", res);
              Toast.show({
                content: "回溯剧情成功",
                type: "success",
              });
              fetchAndSetInitialMessages(sendId);
            });
          }
        },
      });
    },
    [sendId]
  );
  const fetchAndSetInitialMessages = useCallback((chatId) => {
    getChatDetail(chatId).then((res) => {
      console.log("🚀 ~ fetchAndSetInitialMessages ~ res:", res);
      setUseStreaming(true);
      // setUseStreaming(res.mould.stream === 1);
      const allMessages = res.chats || [];
      setChatMessages(allMessages);

      // 设置初始显示的最后 pageSize 条消息
      const initialDisplayed = allMessages.slice(-pageSize);
      setDisplayedMessages(initialDisplayed);

      // 设置分页状态
      setCurrentPage(1);
      setHasMore(allMessages.length > pageSize);

      if (allMessages.length) {
        setLast_id(allMessages[allMessages.length - 1].id);
      } else {
        setLast_id(0);
      }
      setCurrentRoles(res.roles);
      setChatPresets(res.presets);
      setChatPersonas(res.personas);
      setChatDetail(res.detail);
      // 设置当前选中的模型ID
      if (res.detail?.mould_id) {
        setCurrentModelId(res.detail.mould_id);
      }
      
      // 使用 setTimeout 确保 DOM 完全更新后再滚动
      setTimeout(() => {
        console.log('===> 初始化完成，准备滚动到底部');
        scrollToBottom('auto');
      }, 300); // 给予足够的时间让 DOM 更新
    });
  }, [pageSize]);
 
  useEffect(() => {
    if (sendId) {
      fetchAndSetInitialMessages(sendId);
    }
  }, [sendId, fetchAndSetInitialMessages]);
  const backWorldBookDetail = () => {
    customNavigate(`/chatlist?tabType=conversations`);
  };
  const handleEditConfirm = async (updatedContent) => {
    if(!checkCanSendMessage()){
      return
    }
    try {
      // 保存编辑后的消息
      const saveMessage = {
        id: updatedContent.id,
        message: updatedContent.message,
      };
      // 更新本地消息列表
      setChatMessages((prevFull) =>
        prevFull.map((msg) =>
          msg.id === updatedContent.id
            ? { ...msg, message: updatedContent.message }
            : msg
        )
      );
      setDisplayedMessages((prevDisplayed) =>
        prevDisplayed.map((msg) =>
          msg.id === updatedContent.id ? { ...msg, message: updatedContent.message } : msg
        )
      );
      await editChatMessage(saveMessage);
      Toast.show({
        content: "修改成功",
        type: "success",
      });
    } catch (error) {
      Toast.show({
        content: "修改失败，请重试",
        type: "error",
      });
    }
  };
  const formateMessage = (message) => {
    // 先清除HTML标签，但保留换行符
    let cleanMessage = message.replace(/<[^>]*>/g, "");
    // 将连续的换行符替换为单个<br/>标签
    cleanMessage = cleanMessage.replace(/\n/g, "<br/>");
    // 匹配引号中的内容并添加样式
    // cleanMessage = cleanMessage.replace(/("|"|")([^""]+)("|"|")/g, '<em style="color: #8B4513;">$1$2$3</em>');
    cleanMessage = cleanMessage.replace(
      /([""""])([^""]+?)([""""])/g,
      '<em style="color: #db9ea7;">$1$2$3</em>'
    );
    return <div dangerouslySetInnerHTML={{ __html: cleanMessage }} />;
  };
  // 添加重新生成消息的函数
    const regenerateMessage = useCallback(async () => {
      let isViewingLastPage = false;
      
      try {
        // 1. 获取最新消息列表并准备数据
        const currentFullMessages = [...chatMessages];
        const lastFullMessage = currentFullMessages[currentFullMessages.length - 1];
        
        // 2. 如果最后一条是AI消息，先删除它
        if (lastFullMessage && lastFullMessage.id && lastFullMessage.type === 1) {
          await deleteChatMessage({ id: lastFullMessage.id });
          currentFullMessages.pop();
          setChatMessages(currentFullMessages);
          
          if (displayedMessages[displayedMessages.length - 1]?.id === lastFullMessage.id) {
            const currentDisplayMessages = [...displayedMessages];
            currentDisplayMessages.pop();
            setDisplayedMessages(currentDisplayMessages);
          }
        }
  
        if (currentFullMessages.length === 0) {
          Toast.show({ content: "没有可重新生成的消息", type: "error" });
          return;
        }
  
        // 3. 添加AI思考中的临时消息
        const pendingMessage = {
          type: 1,
          message: useStreaming ? "" : "正在思考中...",
          loading: useStreaming ? false : true,
          send_name: currlentRoles.name,
          cover: currlentRoles.cover,
          send_time: dayjs().format("YYYY-MM-DD HH:mm:ss"),
          isStreaming: useStreaming,
          isComplete: false,
        };
        
        isViewingLastPage = displayedMessages.length === 0 || displayedMessages[displayedMessages.length - 1]?.id === lastFullMessage?.id;
        
        setChatMessages([...currentFullMessages, pendingMessage]);
        if (isViewingLastPage) {
          setDisplayedMessages(prev => [...prev.filter(m => m.id !== lastFullMessage?.id), pendingMessage]);
        }
        
        // 4. 构建请求数据
        const messageData = {
          messages: [
            ...chatPresets?.before,
            ...currentFullMessages.map((msg) => ({
              role: msg.type === 0 ? "user" : "assistant",
              content: msg.message,
            })),
            ...chatPresets?.after,
          ],
          stream: useStreaming,
          chat_id: chatDetail.id,
        };
        
        // 5. 发起请求 (复用 sendMessage 的逻辑)
        const xRequestInstance = createXRequestInstance(baseURL);
        let aiMessage = "";
        let total_tokens = 0;
        let shouldAbortDueToError = false;

        if (useStreaming) {
          let isStreamStarted = false;
          const immediateUpdate = (message) => {
            flushSync(() => {
              const updateFunction = (prev) => produce(prev, draft => {
                const last = draft[draft.length - 1];
                if (last?.type === 1) {
                  last.message = message;
                  last.loading = false;
                }
              });
              setChatMessages(updateFunction);
              if (isViewingLastPage) setDisplayedMessages(updateFunction);
            });
            if (isViewingLastPage) scrollToBottom('auto');
          };

          try {
            await xRequestInstance.create(messageData, {
              onError: (error) => {
                if (error.name === "AbortError") {
                  shouldAbortDueToError = true;
                  return;
                }
                const specialErrorCodes = [200014, 200023, 200016];
                if (error.code && specialErrorCodes.includes(error.code)) {
                  Toast.show({ content: parseErrorMessage(error), type: "error" });
                  shouldAbortDueToError = true;
                } else {
                  aiMessage = responseErrorMessage;
                  isStreamStarted = true;
                }
              },
              onUpdate: (msg) => {
                if (msg.data.includes("[DONE]")) {
                  immediateUpdate(aiMessage);
                  return;
                }
                try {
                  const _msg = JSON.parse(msg.data);
                  const deltaContent = _msg?.choices?.[0]?.delta?.content;
                  if (deltaContent) {
                    aiMessage += deltaContent;
                    isStreamStarted = true;
                    immediateUpdate(aiMessage);
                  }
                  if (_msg?.usage?.total_tokens) {
                    total_tokens = _msg.usage.total_tokens;
                  }
                } catch (e) { console.error("解析流式数据失败:", e); }
              },
              onStream: (controller) => { abortController.current = controller; },
            });
          } catch (streamError) {
            if (!shouldAbortDueToError && !isStreamStarted) {
              aiMessage = responseErrorMessage;
              isStreamStarted = true;
            }
          }

          if (shouldAbortDueToError) {
            cleanupUnfinishedMessages();
            return;
          }
          if (!aiMessage.trim()) {
            aiMessage = responseErrorMessage;
          }
        } else {
          try {
            const response = await postChatMessage(messageData);
            if (!response?.choices?.[0]?.message?.content) {
              aiMessage = responseErrorMessage;
            } else {
              aiMessage = response.choices[0].message.content;
              total_tokens = response.usage?.total_tokens || 0;
            }
          } catch (error) {
            aiMessage = responseErrorMessage;
          }
        }
  
        // 6. 处理和保存AI响应
        const replaceFields = chatPresets.replace_fields;
        if (replaceFields.length) {
          replaceFields.forEach((item) => {
            if (item.match_type === "exact") {
              aiMessage = aiMessage.replaceAll(item.search, item?.replace || "");
            }
            if (item.match_type === "regex" && item.search && isValidRegex(item.search)) {
              aiMessage = aiMessage.replaceAll(new RegExp(item.search, "g"), item?.replace || "");
            }
          });
        }
  
        const aiMessageData = {
          type: 1, message: aiMessage, send_name: pendingMessage.send_name,
          send_time: pendingMessage.send_time, send_cover: pendingMessage.cover, total_tokens
        };
        const aiMessageId = await saveMessage(aiMessageData);
  
        // 7. 更新最终消息
        const finalAiMessage = { ...pendingMessage, id: aiMessageId, message: aiMessage, loading: false, isComplete: true };
        
        const finalUpdate = (prev) => {
          const newMessages = [...prev];
          newMessages[newMessages.length - 1] = finalAiMessage;
          return newMessages;
        };
        setChatMessages(finalUpdate);
        if (isViewingLastPage) {
          setDisplayedMessages(finalUpdate);
          setTimeout(() => scrollToBottom('smooth'), 0);
        }
        
        setLast_id(aiMessageId);
        
      } catch (error) {
        console.error("重新生成消息失败:", error);
        cleanupUnfinishedMessages();
        const errorMessage = parseErrorMessage(error);
        if (errorMessage) {
          Toast.show({ content: errorMessage, type: "error" });
        }
      }
    }, [chatMessages, displayedMessages, chatPresets, currlentRoles, useStreaming, chatDetail.id, saveMessage, deleteChatMessage, isValidRegex, scrollToBottom]);
  // 修改 MessageFooter 组件
  const MessageFooter = ({ messageId, messageType, isLastDisplayedMessage }) => {
    // 获取完整的消息对象
    const message = chatMessages.find((msg) => msg.id === messageId);

    const shouldShowRegenerate = useCallback(() => {
      const currentIndex = chatMessages.findIndex(
        (msg) => msg.id === messageId
      );
      // 如果是最后一条消息
      if (isLastDisplayedMessage) return true;
      // 如果是倒数第二条消息，且是用户消息，且最后一条是AI消息
      if (
        currentIndex === chatMessages.length - 2 &&
        messageType === 0 &&
        chatMessages[chatMessages.length - 1]?.type === 1
      ) {
        return true;
      }
      return false;
    }, [messageId, messageType, isLastDisplayedMessage, chatMessages]);

    return (
      <Space>
        <DeleteOutline onClick={() => deleteMessage(messageId, 1)} />
        <EditSOutline onClick={() => editMessage(message)} />
        <ClockCircleOutline onClick={() => deleteMessage(messageId, 2)} />
        {shouldShowRegenerate() && <RedoOutline onClick={regenerateMessage} />}
      </Space>
    );
  };

  // --- 新增：下拉加载更多消息的处理函数 ---
  const loadMoreMessages = async () => {
    if (!hasMore || isLoadingMore) return;
    
    setIsLoadingMore(true);
    
    try {
      // 1. 记录当前第一条消息的位置信息
      const firstVisibleMessage = displayedMessages[0];
      if (!firstVisibleMessage) return;

      console.log('===> 开始加载更多消息，当前第一条消息:', {
        id: firstVisibleMessage.id,
        content: firstVisibleMessage.message
      });

      // 2. 计算要加载的消息范围
      const nextPage = currentPage + 1;
      
      // 修改: 正确计算要加载的消息范围
      // 寻找当前第一条消息在完整消息列表中的位置
      const firstVisibleIndex = chatMessages.findIndex(msg => msg.id === firstVisibleMessage.id);
      if (firstVisibleIndex === -1) {
        console.warn('未找到当前显示的第一条消息在完整消息列表中的位置');
        setIsLoadingMore(false);
        return;
      }
      
      // 计算上一页消息的起始索引，确保不超出数组范围
      const startIndex = Math.max(0, firstVisibleIndex - pageSize);
      // 上一页消息的结束索引就是当前显示的第一条消息的索引
      const endIndex = firstVisibleIndex;
      
      // 获取上一页的消息
      const olderMessages = chatMessages.slice(startIndex, endIndex);

      console.log('===> 准备加载的消息:', {
        startIndex,
        endIndex,
        messageCount: olderMessages.length,
        messageIds: olderMessages.map(m => m.id)
      });

      if (olderMessages.length > 0) {
        // 3. 更新消息列表 - 将新消息添加到当前显示消息的前面
        setDisplayedMessages(prev => [...olderMessages, ...prev]);
        setCurrentPage(nextPage);
        // 只有当还有更多消息可以加载时才设置hasMore为true
        setHasMore(startIndex > 0);

        // 4. 等待 DOM 更新后，滚动到之前的第一条消息位置
        setTimeout(() => {
          const messageElement = document.querySelector(`.ant-bubble[data-message-id="${firstVisibleMessage.id}"]`);
          if (messageElement) {
            console.log('===> 滚动到之前的第一条消息:', firstVisibleMessage.id);
            messageElement.scrollIntoView({ behavior: 'auto', block: 'center' });
          } else {
            console.warn('未找到目标消息元素:', firstVisibleMessage.id);
          }
        }, 100);
      } else {
        setHasMore(false);
      }
    } catch (error) {
      console.error('加载更多消息时出错:', error);
      Toast.show({
        content: '加载消息失败，请重试',
        type: 'error'
      });
    } finally {
      setIsLoadingMore(false);
    }
  };
  // --- 结束 ---

  // --- 新增 Effect: 监听 displayedMessages 更新，处理 AI 回复后的滚动 ---
  useEffect(() => {
    const lastMessage = displayedMessages[displayedMessages.length - 1];
    // 只有在发送新消息时才滚动到底部
    if (
      listRef.current && 
      lastMessage && 
      lastMessage.type === 1 && 
      !lastMessage.loading && 
      !isLoadingMore && 
      isSendingMessage
    ) {
      setTimeout(() => scrollToBottom('smooth'), 50);
    }
  }, [displayedMessages, isLoadingMore, isSendingMessage]); // 添加 isSendingMessage 依赖
  // --- 结束 ---

  // 添加视口高度计算
  useEffect(() => {
    const setViewHeight = () => {
      const vh = window.innerHeight * 0.01;
      document.documentElement.style.setProperty('--vh', `${vh}px`);
    };

    setViewHeight();
    window.addEventListener('resize', setViewHeight);
    window.addEventListener('orientationchange', setViewHeight);

    // 监听软键盘
    window.visualViewport?.addEventListener('resize', setViewHeight);

    return () => {
      window.removeEventListener('resize', setViewHeight);
      window.removeEventListener('orientationchange', setViewHeight);
      window.visualViewport?.removeEventListener('resize', setViewHeight);
    };
  }, []);

  return (
    <div className={styles.page_container}>
      {/* 顶部导航 - 固定 */}
      <div className={styles.header}>
        <HeaderNav
          onBack={backWorldBookDetail}
          title={currlentRoles.name}
          backArrow={true}
          needConfirm={true}
          right={
            <AddOutline
              onClick={() => customNavigate(`/chatImage?id=${chatDetail.id}`)}
            />
          }
        />
      </div>

      {/* 主要角色区域 - 固定 */}
      {currlentRoles.npcs && currlentRoles.npcs.length > 0 && (
        <div className={styles.role_section}>
          <div className={styles.content_body_top_section_title}>
            <p className={styles.title_left}>主要角色</p>
            <p
              className={styles.title_right}
              onClick={() => setIsShowMore(!isShowMore)}
            >
              {isShowMore ? "收起" : "查看"}{" "}
              <span>{isShowMore ? <UpOutline /> : <RightOutline />}</span>
            </p>
          </div>
          {isShowMore && (
            <div className={styles.content_body_top_section}>
              {currlentRoles?.npcs?.map((item) => (
                <div
                  className={styles.content_body_top_section_select}
                  key={item.id}
                >
                  <img src={item.cover} alt="" />
                  <p className={styles.content_body_top_section_select_name}>
                    {item.name}
                  </p>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* 聊天区域 - 可滚动 */}
      <div className={styles.chat_section}>
        <div 
          className={styles.chat_background}
          style={{
            backgroundImage: `url(${chatDetail.image})`,
            backgroundRepeat: "no-repeat",
            backgroundSize: "cover",
            backgroundPosition: "center",
          }}
        />
        <div className={styles.chat_content}>
          <PullToRefresh onRefresh={loadMoreMessages} disabled={!hasMore}>
            <Bubble.List
              ref={listRef}
              roles={roles}
              className={styles.message_list}
              items={React.useMemo(() => 
                displayedMessages.map((message, i) => {
                  const isLastDisplayedMessage = i === displayedMessages.length - 1;
                  return {
                    header: `${message.send_name}  ${message.send_time}`,
                    key: (message.id) || i,
                    role: message.type === 1 ? "assistant" : "user",
                    content:
                      (message.type === 1 && message.isComplete)
                        ? formateMessage(message.message)
                        : message.message,
                    loading: message.loading,
                    footer: message.id && !message.loading ? (
                      <MessageFooter
                        messageId={message.id}
                        messageType={message.type}
                        isLastDisplayedMessage={isLastDisplayedMessage}
                      />
                    ) : null,
                   'data-message-id': message.id || i
                  };
                }), [displayedMessages, currlentRoles]
              )}
            />
          </PullToRefresh>
        </div>
      </div>

      {/* 底部发送区域 */}
      <div className={styles.footer}>
        <ChatInput 
          onSend={handleSendMessage}
          loading={isSendingMessage}
          currentModelId={currentModelId}
          onModelChange={handleModelChange}
          modelVisible={modelVisible}
          setModelVisible={setModelVisible}
          chatId={sendId}
        />
      </div>

      {/* 编辑模态框 */}
      {editVisible && (
        <EditModal
          visible={editVisible}
          setVisible={setEditVisible}
          content={editContent}
          onConfirm={handleEditConfirm}
        />
      )}

      {/* 将 ModelSelector 移到这里 */}
      <ModelSelector
        chatId={sendId}
        visible={modelVisible}
        onClose={() => setModelVisible(false)}
        modelId={currentModelId}
        onModelChange={handleModelChange}
      />
    </div>
  );
};

export default Detail;
